<template>
    <view class="box-picker_position" :style="themeColor">
        <view class="map_wp">
            <map
                id="map_20221212"
                class="picker-map"
                scale="15"
                min-scale="15"
                @regionchange="handleRegionchange"
                :latitude="position.latitude"
                :longitude="position.longitude"
                show-location="true"
                :polygons="polygons"></map>
            <view :class="['picker_map_location', animateLocation ? 'animated' : '']"></view>
        </view>
        <view class="list-picker_position">
            <view class="hd">
                <input type="text" v-model="searchKey" class="input_text" placeholder="请输入搜索地点" />
                <button class="btn-search" type="default" @click="searchPosition">
                    <view class="picker-search"></view>搜索
                </button>
            </view>
            <view class="bd">
                <view>
                    <uni-load-more v-if="isLoading" status="loading"></uni-load-more>
                    <view v-else>
                        <view class="poi-list">
                            <view v-if="searchlist.length > 0" class="poi-list-item flex-s-s">
                                <text class="item-text" v-if="searchlist[0].title"
                                    >当前定位：{{ searchlist[0].title.replace(/\\/g, "") }}</text
                                >
                                <text class="anew" @click="reset">重新定位</text>
                            </view>
                            <view v-if="searchlist.length < 1" class="poi-list-item">
                                <text class="item-text">没有数据</text>
                            </view>
                        </view>
                        <view>
                            <view
                                class="default"
                                :class="activeNum == index ? 'active' : ''"
                                @click="checkFn(item, index)"
                                v-for="(item, index) in storeList">
                                <view class="flex-start">
                                    <image
                                        mode="aspectFill"
                                        class="imagestyle"
                                        :src="easyGetImgUrl(item.ImageUrl)"
                                        alt=""></image>
                                    <view class="info">
                                        <view class="flex-s-s">
                                            <text class="fs28">{{ item.TakeDeliveryName }}</text>
                                            <label class="item-radio">
                                                <view
                                                    class="custom-checkbox"
                                                    :class="{ 'custom-checkbox-checked': activeNum == index }">
                                                    <uni-icons
                                                        type="checkmarkempty"
                                                        v-if="activeNum == index"
                                                        customIcons="icon-white"
                                                        size="32"></uni-icons>
                                                </view>
                                            </label>
                                        </view>
                                        <text class="fs22">距您步行距离：{{ item.Distance.toFixed(2) }}m</text>
                                        <view class="fs24">
                                            <text class="addinfo">地址：{{ item.AddressDetail }}</text>
                                            <view class="call" @click="call(item.ContactTel)"
                                                ><uni-icons type="phone" color="#007AFF" size="32"></uni-icons
                                                ><text class="phone">电话</text></view
                                            >
                                        </view>
                                    </view>
                                </view>
                                <text class="corner" v-if="TakeDeliveryID == item.ID">当前自提点</text>
                            </view>
                            <view v-if="storeList.length < 1" class="poi-list-item">暂无数据</view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="ft">
                <button @click="affirm" class="btn-success">确定</button>
            </view>
        </view>
    </view>
</template>

<script>
import customCheckbox from "@/components/common/custom-checkbox.vue"
import storage from "@/uni-sub-base/utils/storage.js"
import {
    GetUsableTakeDeliveryPage,
    SaveUserTakeDelivery,
    GetUserDefaultTakeDelivery,
} from "@/service/api/takeDelivery.js"
var QQMapWX = require("./qqmap-wx-jssdk.js")
var qqmapsdk, handleRegionchangeTimmer
export default {
    props: {
        polygons: {
            type: Array,
            default: [
                {
                    points: [
                        {
                            latitude: "36.829066",
                            longitude: "118.025761",
                        },
                        {
                            latitude: "36.825012",
                            longitude: "118.066702",
                        },
                        {
                            latitude: "36.81161",
                            longitude: "118.042681",
                        },
                        {
                            latitude: "36.801964",
                            longitude: "118.034875",
                        },
                    ],
                    strokeWidth: 1,
                    strokeColor: "#ff000066",
                    fillColor: "#ff000016",
                },
                {
                    points: [
                        {
                            latitude: "36.817369",
                            longitude: "118.001311",
                        },
                        {
                            latitude: "36.808682",
                            longitude: "118.010281",
                        },
                        {
                            latitude: "36.805555",
                            longitude: "117.996537",
                        },
                    ],
                    strokeWidth: 1,
                    strokeColor: "#ff000066",
                    fillColor: "#ff000016",
                },
            ],
        },
        qqmapsdkKey: {
            type: String,
            default: "",
        },
        base_url: {
            type: String,
            default: "",
        },
        sig: {
            type: String,
            default: "",
        },
        from: {
            type: String,
            default: "",
        },
        pagefrom: {
            type: String,
            default: "",
        },
    },
    components: {
        customCheckbox,
    },
    data() {
        return {
            canConfirm: false,
            animateLocation: false,
            isChangeSelectItem: false,
            searchKey: "",
            position: {
                latitude: "36.811995",
                longitude: "118.05539",
            },
            searchlist: [],
            storeList: [],
            TakeDeliveryID: -1,
            isLoading: true,
            activeItem: {},
            activeNum: -1,
        }
    },

    mounted() {
        if (this.qqmapsdkKey == "") {
            console.error(
                "需要腾讯地图开发Key，申请地址：https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview",
            )
            return
        }
        qqmapsdk = new QQMapWX({
            key: this.qqmapsdkKey,
            BASE_URL: this.base_url,
        })
        let that = this
        let needRegetLocation = true

        if (uni.getStorageSync("mapPickerPosition")) {
            let data = JSON.parse(uni.getStorageSync("mapPickerPosition"))
            if (new Date().getTime() < data.expireTime) {
                needRegetLocation = false
                that.position.latitude = data.position.latitude
                that.position.longitude = data.position.longitude
                that.init()
            }
        }
        if (needRegetLocation) {
            uni.getLocation({
                cacheTimeout: 1,
                accuracy: "best",
                type: "gcj02",
                isHighAccuracy: true,
                success: function (e) {
                    that.position.latitude = e.latitude
                    that.position.longitude = e.longitude
                    uni.setStorageSync(
                        "mapPickerPosition",
                        JSON.stringify({
                            expireTime: new Date().getTime() - 0 + 60 * 1000,
                            position: {
                                latitude: e.latitude,
                                longitude: e.longitude,
                            },
                        }),
                    )
                    that.init()
                },
                fail: function (e) {
                    console.log(e)
                },
            })
        }
        // uni.onLocationChange(function(e){
        // 		that.position.latitude = e.latitude;
        // 		that.position.longitude = e.longitude;
        // 	})
        this.GetDefaultTakeDelivery()
    },
    methods: {
        init() {
            this.animateLocation = true
            handleRegionchangeTimmer = setTimeout(() => {
                this.renderList()
            }, 400)
        },
        renderList() {
            let that = this
            let mapContext = uni.createMapContext("map_20221212", that)
            mapContext.getCenterLocation({
                success: function (rst) {
                    let options = {
                        location: rst.latitude + "," + rst.longitude,
                        get_poi: 1,
                        poi_options: "radius=1000",
                        sig: that.sig,
                        success: function (res) {
                            let isSelect = false
                            if (res.message == "query ok") {
                                that.searchlist = []
                                that.searchlist = res.result.pois
                                that.changeSelectItem(0)
                                that.List(that.searchlist[0].location.lat, that.searchlist[0].location.lng)
                                setTimeout(() => {
                                    that.animateLocation = false
                                }, 200)
                            }
                        },
                        fail: function (error) {
                            console.log(error)
                        },
                    }
                    if (typeof window === "undefined") {
                        delete options.sig
                    }
                    if (options.sig === "") {
                        delete options.sig
                    }
                    qqmapsdk.reverseGeocoder(options)
                },
            })
        },
        reset() {
            let that = this
            let map = JSON.parse(uni.getStorageSync("mapPickerPosition"))
            that.position.latitude = map.position.latitude
            that.position.longitude = map.position.longitude
        },
        GetDefaultTakeDelivery() {
            GetUserDefaultTakeDelivery({}).then((res) => {
                if (res.State == 1) {
                    this.TakeDeliveryID = res.Data.ID
                }
            })
        },
        call(phone) {
            uni.makePhoneCall({
                phoneNumber: phone,
            })
        },
        affirm() {
            if (!this.activeItem.ID) {
                this.easyToast("请选择提货点")
                return
            }
            SaveUserTakeDelivery({ takeDeliveryId: this.activeItem.ID }).then((res) => {
                if (res.State == 1) {
                    if (this.from == "selectBack") {
                        // uni.navigateBack()
                        uni.redirectTo({
                            url: "/pages/group/cart/index",
                        })
                    } else if (this.from == "productBack") {
                        uni.redirectTo({
                            url: "/pages/group/index",
                        })
                    } else if (this.pagefrom == "cart") {
                        // eventBus.$emit('CHANGE_TAB', 'group')
                        // let pages = getCurrentPages()
                        // if (pages.length > 1) {
                        // 	//回到首页
                        // 	uni.navigateBack({
                        // 		delta: getCurrentPages().length
                        // 	});
                        // }
                        uni.redirectTo({
                            url: "/pages/group/cart/index",
                        })
                    } else if (this.pagefrom == "product") {
                        uni.redirectTo({
                            url: "/pages/group/index",
                        })
                    }
                }
            })
        },
        searchPosition() {
            if (this.searchKey.replace(/\s+/, "") == "") {
                return
            }
            let that = this
            let searchOptions = {
                keyword: this.searchKey,
                // location:{
                // 	latitude:this.position.latitude,
                // 	longitude:this.position.longitude
                // },
                sig: that.sig,
                success: function (rst) {
                    let isSelect = false
                    if (rst.message == "query ok") {
                        that.searchlist = []
                        that.searchlist = rst.data
                        that.changeSelectItem(0)
                        that.List(that.searchlist[0].location.lat, that.searchlist[0].location.lng)
                    }
                },
            }
            if (typeof window === "undefined") {
                delete searchOptions.sig
            }
            if (searchOptions.sig === "") {
                delete searchOptions.sig
            }

            qqmapsdk.search(searchOptions)
        },
        changeSelectItem(index) {
            // if(this.searchlist[index].useable){
            for (let i = 0; i < this.searchlist.length; i++) {
                let temp = {}
                for (var key in this.searchlist[i]) {
                    temp[key] = this.searchlist[i][key]
                }
                if (i === index) {
                    this.position.latitude = temp.location.lat
                    this.position.longitude = temp.location.lng
                }

                // this.$set(this.searchlist,i,temp);
            }
            // }
        },
        handleRegionchange(e) {
            this.isLoading = true
            console.log(e)
            if (e.type == "end") {
                if (handleRegionchangeTimmer) {
                    clearTimeout(handleRegionchangeTimmer)
                }
                handleRegionchangeTimmer = setTimeout(() => {
                    this.renderList()
                }, 400)
                // this.changeSelectItem(0)
            }
        },

        isPointInPolygon(aLat, aLon, pointList) {
            /* 
			            :param aLon: double 经度 
			            :param aLat: double 纬度 
			            :param pointList: list [{latitude: 22.22, longitude: 113.113}...] 多边形点的顺序需根据顺时针或逆时针，不能乱 
			            */
            var iSum = 0
            var iCount = pointList.length

            if (iCount < 3) {
                return false
            }
            //  待判断的点(x, y) 为已知值
            var y = aLat
            var x = aLon
            for (var i = 0; i < iCount; i++) {
                var y1 = pointList[i].latitude
                var x1 = pointList[i].longitude
                if (i == iCount - 1) {
                    var y2 = pointList[0].latitude
                    var x2 = pointList[0].longitude
                } else {
                    var y2 = pointList[i + 1].latitude
                    var x2 = pointList[i + 1].longitude
                }
                // 当前边的 2 个端点分别为 已知值(x1, y1), (x2, y2)
                if ((y >= y1 && y < y2) || (y >= y2 && y < y1)) {
                    //  y 界于 y1 和 y2 之间
                    //  假设过待判断点(x, y)的水平直线和当前边的交点为(x_intersect, y_intersect)，有y_intersect = y
                    // 则有（2个相似三角形，公用顶角，宽/宽 = 高/高）：|x1 - x2| / |x1 - x_intersect| = |y1 - y2| / |y1 - y|
                    if (Math.abs(y1 - y2) > 0) {
                        var x_intersect = x1 - ((x1 - x2) * (y1 - y)) / (y1 - y2)
                        if (x_intersect < x) {
                            iSum += 1
                        }
                    }
                }
            }
            if (iSum % 2 != 0) {
                //true就是在
                return true
            } else {
                //false就是不在
                return false
            }
        },
        confirmSelect() {
            if (this.canConfirm) {
                this.searchlist.forEach((val) => {
                    if (val.select) {
                        val.polygonIndex = []
                        this.polygons.forEach((polygon, index) => {
                            if (this.isPointInPolygon(val.location.lat, val.location.lng, polygon.points)) {
                                val.polygonIndex.push(index)
                            }
                        })
                        uni.setStorageSync("polygonLocationPicker", JSON.stringify(val))
                        this.$emit("selected", JSON.stringify(val))
                    }
                })
            }
        },
        List(latitude, longitude) {
            let param = {
                lat: latitude,
                lng: longitude,
                pageIndex: 1,
                pageSize: 20,
            }
            GetUsableTakeDeliveryPage(param).then((res) => {
                this.isLoading = false
                if (res.Data) {
                    for (let i = 0; i < res.Data.length; i++) {
                        let item = res.Data[i]
                        if (item.ImageUrl && item.ImageUrl.indexOf(",") > -1) {
                            item.ImageUrl = item.ImageUrl.slice(0, item.ImageUrl.indexOf(","))
                        }
                    }
                    this.storeList = res.Data
                }
            })
        },
        checkFn(item, index) {
            this.activeNum = index
            this.activeItem = item
        },
    },
}
</script>

<style scoped lang="scss">
@keyframes bounceInDown {
    from,
    20%,
    53%,
    to {
        animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
        transform: translate3d(0, 0, 0);
    }

    40%,
    43% {
        animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
        transform: translate3d(0, -30rpx, 0) scaleY(1.1);
    }

    70% {
        animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
        transform: translate3d(0, -15rpx, 0) scaleY(1.05);
    }

    80% {
        transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
        transform: translate3d(0, 0, 0) scaleY(0.95);
    }

    90% {
        transform: translate3d(0, -4rpx, 0) scaleY(1.02);
    }
}

.box-picker_position {
    height: 100%;
    width: 100%;
    background: #fff;
    display: flex;
    flex-flow: column;
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
}
.map_wp {
    position: relative;
    width: 750rpx;
    height: 400rpx;
}
.picker_map_location {
    width: 60rpx;
    height: 60rpx;
    background-image: url("data:image/svg+xml,%3Csvg t='1670988557938' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='3498' width='200' height='200'%3E%3Cpath d='M511.968 0c-207.84 0-376.96 169.12-376.96 376.992 0 54.208 11.104 105.984 32.96 153.888 94.24 206.24 274.976 424 328.128 485.824 3.968 4.608 9.792 7.296 15.904 7.296s11.904-2.656 15.904-7.296c53.12-61.824 233.856-279.552 328.128-485.824 21.888-47.904 32.96-99.648 32.96-153.888-0.032-207.872-169.152-376.992-376.992-376.992zM511.968 572.8c-107.968 0-195.808-87.84-195.808-195.808s87.84-195.84 195.808-195.84 195.808 87.84 195.808 195.84c0 107.968-87.84 195.808-195.808 195.808z' fill='%23fa3c23' p-id='3499'%3E%3C/path%3E%3C/svg%3E");
    background-size: cover;
    background-position: center bottom;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -30rpx;
    margin-top: -60rpx;
    z-index: 999;
    transform-origin: center bottom;
}
.picker_map_location.animated {
    animation: bounceInDown 0.6s linear infinite;
}
.picker-map {
    width: 750rpx;
    height: 400rpx;
}
.list-picker_position {
    position: relative;
    flex: 1;
    display: flex;
    flex-flow: column;
    overflow: hidden;
    .hd {
        padding: 20rpx 20rpx 10rpx;
        display: flex;
        .input_text {
            flex: 1;
            box-sizing: border-box;
            background: #f2f2f2;
            border-radius: 6rpx;
            height: 60rpx;
            font-size: 28rpx;
            padding-left: 1em;
        }
    }
    .bd {
        padding: 20rpx;
        box-sizing: border-box;
        flex: 1;
        overflow-y: scroll;
        .item {
            display: flex;
            padding: 15rpx 10rpx;
            border-bottom: 1px solid #ccc;
            line-height: 1.92;
            align-items: stretch;
            .title {
                font-size: 32rpx;
            }
            .address {
                font-size: 24rpx;
                color: #999;
                line-height: 1.5;
            }
        }
        .item-l {
            padding: 10rpx 6rpx 0 0;
        }
        .item-c {
            flex: 1;
        }
        .item-r {
            width: 60rpx;
            display: flex;
            align-items: center;
            align-content: center;
        }
        .item.disabled {
            opacity: 0.5;
        }
    }
}
.btn-search {
    background: #007aff;
    font-size: 24rpx;
    color: #fff;
    display: flex;
    padding: 0;
    align-items: center;
    justify-content: center;
    width: 120rpx;
}
.btn-selected {
    background: #007aff;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    color: #fff;
    border: none;
    border-radius: 0;
}
.btn-selected.disabled {
    background: #f2f2f2;
    color: #ccc;
}
.poi-list {
    background: $color-white;
    display: flex;
    flex-direction: column;
}

.poi-list-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 70rpx;
    border-bottom: solid 1px $border;
}

.item-text {
    font-size: $font-size-28;
}

.scroll {
    background: $color-white;
    border-radius: 48rpx 48rpx 0px 0px;
}
.flex-s-s {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;
    .item-text {
        color: #333333;
        font-size: 30rpx;
        font-weight: bold;
    }
}
.anew {
    font-size: 24rpx;
    color: #007aff;
}
.title {
    width: 208rpx;
    height: 60rpx;
    background: $app-color-main;
    border-radius: 24rpx 0px 24rpx 0px;
    font-size: 32rpx;
    color: #ffffff;
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 24rpx;
}
.imagestyle {
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx;
    margin-right: 16rpx;
}
.default {
    background: #fffcfc;
    border-radius: 12rpx;
    border: 1rpx solid #cbcbcb;
    margin: 0 0rpx 14rpx 0rpx;
    padding: 24rpx;
    position: relative;
}
.flex-start {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: row;
}
.info {
    flex: 1;
    height: 160rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.fs28 {
    font-size: 28rpx;
    font-weight: bold;
}
.fs22 {
    font-size: 24rpx;
    color: #fc0d2c;
}
.fs24 {
    font-size: 24rpx;
    color: #666;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;
}
.addinfo {
    font-size: 24rpx;
    flex-wrap: wrap;
    flex: 1;
}
.call {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-left: 10rpx;
}
.phone {
    font-size: 24rpx;
    color: #007aff;
}
.icon-color {
    color: #007aff;
}
.corner {
    position: absolute;
    left: 0;
    top: 0;
    width: 138rpx;
    height: 40rpx;
    background: #eb1010;
    font-size: 20rpx;
    color: #fff;
    z-index: 1000000;
    border-radius: 12rpx 0px 12rpx 0px;
    text-align: center;
    line-height: 40rpx;
}
.active {
    border-color: #eb1010;
}

.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background: $color-white;
    box-shadow: 0px -3px 38px 0px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 0 $app-page-padding;
    z-index: 2;
    padding-bottom: constant(safe-area-inset-bottom);
    /*兼容 IOS<11.2*/
    padding-bottom: env(safe-area-inset-bottom);
    /*兼容 IOS>11.2*/
}
.btn {
    height: 88rpx;
    line-height: 88rpx;
    font-size: 32rpx;
    text-align: center;
    border-radius: 55rpx;
    color: #fff !important;
    background: #eb1010;
    width: 690rpx;
}
.custom-checkbox {
    width: 34rpx;
    height: 34rpx;
    border-radius: 44rpx;
    border: solid 1rpx $app-color-text-tip;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 1;
}
.custom-checkbox-checked {
    background: $app-color-main;
    border-color: $app-color-main;
}
</style>
